var express = require('express');
const db = require('../db/index1.js')
var router = express.Router();


/* GET users listing. */
router.get('/', function (req, res, next) {
    db('select * from user', (err, result) => {
        res.send({
            code: 200,
            msg: "接口地址",
            data: result
        })
    })

});

// 登陆
router.get('/login', function (req, res, next) {
    let data = req.query
    let sql = `select * from user where name= "${data.name}" and password = "${data.password}" and email = "${data.email}"`;
    db(sql, (err, result) => {
        if (err) throw err;
        if (Object.keys(result).length) {
            res.send({
                data: {
                    code: 200,
                    msg: `登陆成功`
                }
            })
        } else {
            let sql = `select * from user where name= "${data.name}"`
            db(sql, (err, result) => {
                if (err) throw err;
                if (Object.keys(result).length) {
                    res.send({
                        data: {
                            code: 404,
                            msg: '用户名或密码错误'
                        }
                    })
                } else {
                    res.send({
                        data: {
                            coe: 401,
                            msg: '此用户不存在'
                        }
                    })
                }
            })
        }
    })
});

// 注册
router.all('/sign', (req, res) => {
    let data = ''
    if (Object.keys(req.query).length) {
        data = req.query
    } else {
        data = req.body
    }
    console.log('注册:' + data);
    let sql = `select * from user where name= "${data.name}"`;
    db(sql, (err, result) => {
        if (err) throw err;
        if (Object.keys(result).length) {
            res.send({
                code: 404,
                msg: '此用户已存在'
            })
        } else {
            let sql = `INSERT INTO user (name, password, email) VALUES ('${data.name}', '${data.password}', '${data.email}')`
            db(sql, (err, result) => {
                if (err) throw err
                res.send({
                    code: 200,
                    msg: '注册成功'
                })
            })
        }
    })
})

// 修改密码
router.get('/update', (req, res) => {
    let data = req.query
    console.log(data);
    let sql = `UPDATE user SET password = '${data.password}' WHERE email = '${data.email}'`
    db(sql, (err, result) => {
        if (err) throw err
        res.send({
            code: 200,
            msg: '修改成功'
        })
    })
})


module.exports = router;
